<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row>
        <el-col :span="4">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddBank"
            >新增银行账户</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="bankList"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          align="center"
          label="银行"
          prop="account"
        ></el-table-column>
        <el-table-column
          align="center"
          label="金额(元)"
          prop="money"
          width="100"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column
          align="center"
          label="备注"
          prop="desc"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑银行账户' : '新增银行账户'"
      width="30%"
    >
      <el-form
        :model="bankForm"
        :rules="bankFormRules"
        ref="bankFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="银行" prop="account">
          <el-input
            type="text"
            v-model="bankForm.account"
            placeholder="银行"
            clearable
          />
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input
            type="number"
            step="0.01"
            v-model="bankForm.money"
            placeholder="输入金额"
            clearable
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input v-model="bankForm.desc" placeholder="备注" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveBank">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBanks, addBank, updateBank, delBank } from "@/api/bank";

const defaultForm = {
  id: undefined,
  account: "",
  money: 0,
  desc: "",
};

export default {
  name: "Bank",
  data() {
    return {
      bankForm: Object.assign({}, defaultForm),
      bankFormRules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      },
      dialogVisible: false,
      dialogType: "new",
      bankList: [],
      listLoading: true,
    };
  },
  created() {
    this.getBanks();
  },
  methods: {
    // 员工列表
    getBanks() {
      this.listLoading = true;
      const params = {
        hidden: "1",
      };
      getBanks(params)
        .then((res) => {
          this.bankList = res;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "money") {
        return row.money.toFixed(2);
      } else {
        return cellValue;
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "money") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });

      return sums;
    },
    // 增加银行账户
    handleAddBank() {
      this.bankForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.bankFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.bankForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["bankFormRef"].clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该账户吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delBank(row.id);

          this.bankList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("账户信息删除失败!");
        });
    },
    // 保存操作
    async SaveBank() {
      this.$refs.bankFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          const res = await updateBank(this.bankForm);
          console.log(isEdit, res);
          const index = this.bankList.findIndex((v) => v.id === res.id);
          this.bankList.splice(index, 1, res);
        } else {
          const res = await addBank(this.bankForm);
          const { id } = res;
          if (id > 0) {
            this.getBanks();
          }
        }

        const { account } = this.bankForm;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>银行账户: ${account}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .box-card{
  //   margin-top: 30px;
  // }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .el-select {
    width: 100%;
  }
}
</style>